package com.cdplife.ci.modular.system.service.impl;

import cn.stylefeng.roses.core.reqres.response.SuccessResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import cn.stylefeng.roses.kernel.model.exception.ServiceException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.cdplife.ci.core.common.exception.BizExceptionEnum;
import com.cdplife.ci.core.shiro.ShiroKit;
import com.cdplife.ci.modular.system.model.InsuranceKind;
import com.cdplife.ci.modular.system.model.PlanInsuranceKind;
import com.cdplife.ci.modular.system.model.PolicyPlan;
import com.cdplife.ci.modular.system.dao.PolicyPlanMapper;
import com.cdplife.ci.modular.system.service.IInsuranceKindService;
import com.cdplife.ci.modular.system.service.IPlanInsuranceKindService;
import com.cdplife.ci.modular.system.service.IPolicyPlanService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 保单保障计划表 服务实现类
 * </p>
 *
 * @author jers
 * @since 2018-11-07
 */
@Service
public class PolicyPlanServiceImpl extends ServiceImpl<PolicyPlanMapper, PolicyPlan> implements IPolicyPlanService {


    @Autowired
    private IInsuranceKindService insuranceKindService;
    @Autowired
    private IPlanInsuranceKindService planInsuranceKindService;

    protected static SuccessResponseData SUCCESS_TIP = new SuccessResponseData();
    /**
     * 获取保单保障计划列表,加上险种名称字符串集合
     */
    @Override
    public List<Map<String, Object>> selectPolicyPlanList(Integer policyId){
        //保单中的计划列表
        List<Map<String, Object>> policyPlans = this.baseMapper.selectPolicyPlanList(policyId);
        //获取计划ID集合
        List<Long> planIds = new ArrayList();
        for (Map<String, Object> policyPlan:policyPlans){
            planIds.add((Long)policyPlan.get("id"));
        }
        //获取计划险种信息
        List<Map<String, Object>> planInsuranceKinds = planInsuranceKindService.getInsuranceNameByBatchIds(planIds,1);
        for (Map<String, Object> policyPlan:policyPlans){
            for (Map<String, Object> planInsuranceKind:planInsuranceKinds){
                if(policyPlan.get("id") == planInsuranceKind.get("plan_id")){
                    policyPlan.put("insurance_names",planInsuranceKind.get("insurance_names"));
                    break;
                }
            }
        }
        return policyPlans;
    }

    /**
     * 获取某个保单保障计划及险种列表 【查看计划】
     */
    @Override
    public Map<String, Object> getInsuranceKindList(Integer policyPlanId){
        Map<String, Object> result = new HashMap<>();
        //如果删除了的保障计划？
        PolicyPlan PolicyPlan = this.baseMapper.selectById(policyPlanId);
        result.put("policyPlan",PolicyPlan);
        //获取险种列表
        List<Map<String, Object>> insuranceKinds = insuranceKindService.selectInsuranceKindList(PolicyPlan.getPolicyId());
        //获取计划险种
        List<PlanInsuranceKind> planInsuranceKinds = planInsuranceKindService.getPlanInsuranceKindList(policyPlanId,1);
        //组合险种与计划险种
        for(Map<String, Object> insuranceKindMap:insuranceKinds){
            long insuranceKindId = (Long) insuranceKindMap.get("id");
            //该险种是否已加入到保障计划
            boolean flag = false;
            for(PlanInsuranceKind planInsuranceKind : planInsuranceKinds){
                if(planInsuranceKind.getInsuranceKindId() == insuranceKindId){
                    flag = true;
                    insuranceKindMap.put("hasSelect",1);
                    insuranceKindMap.put("salaryTimes",planInsuranceKind.getSalaryTimes());
                    break;
                }
            }
            if(!flag){
                insuranceKindMap.put("hasSelect",0);
                insuranceKindMap.put("salaryTimes","");
            }
        }
        result.put("insuranceKind",insuranceKinds);
        return result;
    }

    /**
     * @brief 保存保单保障计划险种
     * @param policyPlanId
     * @param data
     * @return
     */
    @Transactional
    public Object saveInsuranceKind(Integer policyPlanId,String data){
        try{
            //获取保障计划ID的旧险种
            List<PlanInsuranceKind> planInsuranceKinds = planInsuranceKindService.getPlanInsuranceKindList(policyPlanId,1);
            //保障计划信息
            PolicyPlan PolicyPlan = this.baseMapper.selectById(policyPlanId);
            //获取险种列表
            List<Map<String, Object>> insuranceKinds = insuranceKindService.selectInsuranceKindList(PolicyPlan.getPolicyId());
            //提交的数据 字符串转json
            JSONArray jsonArray = JSON.parseArray(data);
            PlanInsuranceKind planInsuranceKindNew = new PlanInsuranceKind();
            //遍历
            for (Object obj : jsonArray) {
                JSONObject jsonObject = (JSONObject) obj;
                //是否新数据
                boolean flag = true;
                for(PlanInsuranceKind planInsuranceKind : planInsuranceKinds){
                    //已保存过的数据
                    if(planInsuranceKind.getInsuranceKindId() == jsonObject.getInteger("id")){
                        //更新
                        if(jsonObject.getInteger("hasSelect") == 1){
                            planInsuranceKind.setSalaryTimes(jsonObject.getInteger("salaryTimes"));
                            planInsuranceKind.updateById();
                        }else{  //删除
                            planInsuranceKind.deleteById();
                        }
                        flag = false;
                        break;
                    }
                }
                //新增
                if(flag && jsonObject.getInteger("hasSelect") == 1){
                    planInsuranceKindNew.setSalaryTimes(jsonObject.getInteger("salaryTimes"));
                    planInsuranceKindNew.setPlanId(policyPlanId);
                    planInsuranceKindNew.setPlanType(1);
                    planInsuranceKindNew.setInsuranceKindId(jsonObject.getInteger("id"));
                    InsuranceKind insuranceKind = insuranceKindService.selectById(jsonObject.getInteger("id"));
                    planInsuranceKindNew.setAmountType(insuranceKind.getAmountType());
                    planInsuranceKindNew.setAmountLimit(insuranceKind.getAmountLimit());
                    planInsuranceKindNew.setAmount(insuranceKind.getAmount());
                    planInsuranceKindNew.insert();
                }
            }
        }catch (Exception e){
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        return SUCCESS_TIP;
    }

    /**
     * 获取单个保单保障计划信息
     */
    public Map<String, Object> getPolicyPlanInfo(Integer policyPlanId){
        Map<String, Object> result = new HashMap<>();
        PolicyPlan policyPlan = this.baseMapper.selectById(policyPlanId);
        result.put("policyPlan",policyPlan);
        //获取计划险种
        List<Map<String, Object>> planInsuranceKinds = planInsuranceKindService.getInsuranceListByBatchIds(policyPlanId.longValue(),1);
        result.put("planInsuranceKinds",planInsuranceKinds);
        return result;
    }
    /**
     * 获取保单下所有保障计划信息以及险种信息
     */
    public Map<Integer, Object> getPolicyPlanListByPolicyId(Integer policyId){
        //保单中的计划列表
        Map<Integer, Object> result = new HashMap<>();
        List<Map<String, Object>> policyPlans = this.baseMapper.selectPolicyPlanList(policyId);
        for (Map<String, Object> policyPlan : policyPlans){
            Long policyPlanIdTmp = (Long)policyPlan.get("id");
            int policyPlanId = policyPlanIdTmp.intValue();
            result.put(policyPlanId,this.getPolicyPlanInfo(policyPlanId)) ;
        }
        return result;
    }
    /**
     * 增加保障计划
     */
    public Object addPolicyPlan(PolicyPlan policyPlan){
        Object result = validate(policyPlan);
        if(result != null){
            return result;
        }
        if(policyPlan.getPolicyId() == null){
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        try {
            //校验重复保单ID与险种CODE
            Wrapper<PolicyPlan> wrapper = new EntityWrapper<PolicyPlan>();
            wrapper = wrapper.eq("policy_id", policyPlan.getPolicyId()).and().eq("policy_plan_code",policyPlan.getPolicyPlanCode()).and().eq("is_del",0);
            List<PolicyPlan> insuranceKinds = this.baseMapper.selectList(wrapper);
            if (insuranceKinds != null && insuranceKinds.size() > 0) {
                throw new ServiceException(BizExceptionEnum.EXISTED_THE_ERROR);
            }
            policyPlan.setCreatedBy(ShiroKit.getUser().getId().toString());
            policyPlan.setLastModifiedBy(ShiroKit.getUser().getId().toString());
            policyPlan.insert();
            return SUCCESS_TIP;
        }catch (Exception e){
            e.printStackTrace();
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
    }
    /**
     * 修改保障计划
     */
    public Object updatePolicyPlan(PolicyPlan policyPlan){
        Object result = validate(policyPlan);
        if(result != null){
            return result;
        }
        if(policyPlan.getId() == null){
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        try {
            //修改的条件限制
            //to do
            //设置当前险种
            policyPlan.setLastModifiedBy(ShiroKit.getUser().getId().toString());
            policyPlan.updateById();
            return SUCCESS_TIP;
        }catch (Exception e){
            e.printStackTrace();
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
    }
    /**
     * 删除保障计划
     */
    public Object deletePolicyPlan(Integer policyPlanId){

        try {
            //删除的条件 。。。
            //to do
            PolicyPlan policyPlan = this.baseMapper.selectById(policyPlanId);
            policyPlan.setCreatedBy(ShiroKit.getUser().getId().toString());
            policyPlan.setIsDel(1);
            policyPlan.updateById();
            return SUCCESS_TIP;
        }catch (Exception e){
            e.printStackTrace();
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
    }

    /**
     * @brief 过滤条件
     * @param policyPlan
     * @return
     */
    private Object validate(PolicyPlan policyPlan){
        //校验空字符
        if (ToolUtil.isOneEmpty(
                policyPlan.getPolicyPlanCode(),policyPlan.getPolicyPlanName())) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        //险种code大于4位
        if(policyPlan.getPolicyPlanCode().length() > 4){
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        return null;
    }

}
